<style lang="scss">

</style>
<template>
  <div>
    <div class="col-md-12">
      <section>
        <div>
          <h3 class="col-header">
            <span class="bottom" />
            <span class="line" />
            <span class="label-angle" />
            <span class="label">人员信息管理</span>
          </h3>
          <div class="query_org">
            <div class="row form-group form-group-sm">
              <el-form
                ref="queryParam" class="form-horizontal j-forms" :model="queryParam"
                label-width="100px"
              >
                <el-form-item label="管理机构" prop="agencyCode" class="col-md-4">
                  <el-select
                    v-model="queryParam.agencyCode"
                    class="col-md-12" clearable
                    placeholder="请选择" filterable
                  >
                    <el-option
                      v-for="item in orgOption" :key="item.code" :label="(item.code + '-' + item.name)"
                      :value="item.code"
                    />
                  </el-select>
                </el-form-item>
                <el-form-item label="营业区" prop="tradeRegionCode" class="col-md-4">
                  <el-select
                    v-model="queryParam.tradeRegionCode"
                    class="col-md-12" clearable
                    placeholder="请选择" filterable
                  >
                    <el-option
                      v-for="item in regionOption" :key="item.code" :label="(item.code + '-' +item.name)"
                      :value="item.code"
                    />
                  </el-select>
                </el-form-item>
                <el-form-item label="营业部" prop="tradeDeptCode" class="col-md-4">
                  <el-select
                    v-model="queryParam.tradeDeptCode"
                    class="col-md-12" clearable
                    placeholder="请选择" filterable
                  >
                    <el-option
                      v-for="item in deptOption" :key="item.code" :label="(item.code + '-' +item.name)"
                      :value="item.code"
                    />
                  </el-select>
                </el-form-item>
                <el-form-item label="业务员代码" prop="agentCode" class="col-md-4">
                  <el-input
                    v-model="queryParam.agentCode" class="col-md-12"
                    placeholder="请输入业务员代码"
                  />
                </el-form-item>
                <el-form-item label="业务员名称" prop="agentName" class="col-md-4">
                  <el-input
                    v-model="queryParam.agentName" class="col-md-12"
                    placeholder="请输入业务员姓名"
                  />
                </el-form-item>
                <el-form-item label="业务员证件类型" prop="certificationType" class="col-md-4">
                  <el-select
                    v-model="queryParam.certificationType"
                    class="col-md-12" clearable
                    placeholder="请选择"
                  >
                    <el-option
                      v-for="item in documentTypeOptions" :key="item.code" :label="item.name"
                      :value="item.code"
                    />
                  </el-select>
                </el-form-item>
                <el-form-item label="业务员证件号码" prop="certificateNum" class="col-md-4">
                  <el-input
                    v-model="queryParam.certificateNum" class="col-md-12"
                    placeholder="请输入证件号码"
                  />
                </el-form-item>
                <el-form-item label="审核状态" prop="approvalStatus" class="col-md-4">
                  <el-select
                    v-model="queryParam.approvalStatus"
                    class="col-md-12" clearable
                    placeholder="请选择"
                  >
                    <el-option
                      v-for="item in approvalStatusOption" :key="item.code" :label="item.name"
                      :value="item.code"
                    />
                  </el-select>
                </el-form-item>
                <el-form-item label="人员状态" prop="personnelStatus" class="col-md-4">
                  <el-select
                    v-model="queryParam.personnelStatus"
                    class="col-md-12" clearable
                    placeholder="请选择"
                  >
                    <el-option
                      v-for="item in personnelStatusOptions" :key="item.code" :label="item.name"
                      :value="item.code"
                    />
                  </el-select>
                </el-form-item>
                <el-form-item label="职级" prop="personnelRankCode" class="col-md-4">
                  <el-select
                    v-model="queryParam.personnelRankCode"
                    class="col-md-12" clearable
                    placeholder="请选择"
                  >
                    <el-option
                      v-for="item in rankOptions" :key="item.code" :label="item.name"
                      :value="item.code"
                    />
                  </el-select>
                </el-form-item>
                <el-form-item label="入司时间" class="col-md-4">
                  <el-date-picker
                    v-model="dateRange"
                    class="el-col-md-11 width-p45" type="daterange"
                    data-type="string" :editable="false"
                    placeholder="请选择日期范围"
                    @change="getTimeRange"
                  />
                </el-form-item>
              </el-form>
            </div>
          </div>
          <div class="row form-group col-md-12" style="text-align : center; margin:20px 0">
            <rich-button
              :plain="true" type="info" shape="capsule"
              class="el-icon-search" @click="searchQuery"
            >
              查询
            </rich-button>
            <rich-button shape="capsule" class="el-icon-quit" @click="reset">
              重置
            </rich-button>
          </div>
          <div>
            <el-button :plain="true" type="info" @click="addRow">
              人员信息录入
            </el-button>
            <el-button :plain="true" type="info" @click="$refs.ImportExcel.downloadTemplate()">
              下载模板
            </el-button>
            <el-button :plain="true" type="info" @click="importData">
              批量导入
            </el-button>
            <el-table
              ref="table"
              class="el-table-guding"
              :data="rows"
              style="width:100%"
            >
              <el-table-column type="index" label="序号" />
              <el-table-column prop="agentCode" label="业务员代码" width="110" />
              <el-table-column prop="agentName" label="业务员姓名" />
              <el-table-column prop="certificateType" label="业务员证件类型" width="100">
                <template slot-scope="scope">
                  {{ optionShowLabel(documentTypeOptions,scope.row.certificateType) }}
                </template>
              </el-table-column>
              <el-table-column prop="certificateNum" label="业务员证件号码" width="160" />
              <el-table-column prop="personnelRankCode" label="职级" width="100">
                <template slot-scope="scope">
                  {{ optionShowLabel(rankOptions,scope.row.personnelRankCode) }}
                </template>
              </el-table-column>
              <el-table-column prop="agencyName" label="管理机构" width="250">
                <template slot-scope="scope">
                  {{ scope.row.agencyName + ' ' + scope.row.agencyCode }}
                </template>
              </el-table-column>
              <el-table-column prop="tradeRegionName" label="营业区" width="250">
                <template slot-scope="scope">
                  {{ scope.row.tradeRegionName + ' ' + scope.row.tradeRegionCode }}
                </template>
              </el-table-column>
              <el-table-column prop="tradeDeptName" label="营业部" width="250">
                <template slot-scope="scope">
                  {{ scope.row.tradeDeptName + ' ' + scope.row.tradeDeptCode }}
                </template>
              </el-table-column>
              <el-table-column prop="personnelStatus" label="人员状态">
                <template slot-scope="scope">
                  {{ optionShowLabel(personnelStatusOptions,scope.row.personnelStatus) }}
                </template>
              </el-table-column>
              <el-table-column prop="approvalStatus" label="审核状态">
                <template slot-scope="scope">
                  {{ optionShowLabel(approvalStatusOption,scope.row.approvalStatus) }}
                </template>
              </el-table-column>
              <el-table-column prop="updCode" label="操作员" width="130" />
              <el-table-column prop="updTm" label="操作时间" width="150" />
              <el-table-column
                label="操作" width="130" fixed="right"
              >
                <template slot-scope="scope">
                  <el-button
                    type="text" size="small"
                    @click="seeRow(scope.row)"
                  >
                    查看
                  </el-button>
                  <!-- v-if="scope.row.approvalStatus === '1'" -->
                  <el-button
                    v-if="scope.row.approvalStatus === '1'"
                    type="text" size="small"
                    @click="editRow(scope.row)"
                  >
                    编辑
                  </el-button>
                  <!-- 0 通过 1-未通过 2-审核中 -->
                  <el-button
                    v-if="scope.row.approvalStatus === '1'"
                    type="text" size="small"
                    @click="delRow(scope.row)"
                  >
                    删除
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
            <el-pagination
              style="text-align: right;" :current-page="pageNo" :page-sizes="[10, 20, 30, 50, 100]"
              :page-size="pageSize" layout="total, sizes, prev, pager, next, jumper" :total="total"
              @size-change="handleSizeChange" @current-change="handleCurrentChange"
            />
          </div>
        </div>
      </section>
      <ImportExcel
        ref="ImportExcel" :import-exel-dialog-show="importExelDialogShow" template-id="3"
        :path="'/tbagentinfo/import/excel'" @importExcelClose="importExelDialogShow =false" @query="query"
      />
      <Delete :is-show="isShow" @delRow="deleteRow" @close="isShow = false" />
    </div>
  </div>
</template>
<script>
import { deletePersonAPi, getApprovalIdApi, getOrgOptionAPi, getRegionOptionAPi, getDeptOptionAPi, getDictOptionsApi } from '@/modules/index/src/common/common-api';
import { axios } from 'utils/https';
import ImportExcel from '@/modules/index/src/components/importExcel.vue';
import Delete from '@/modules/index/src/components/del-Module.vue';
import { getOper } from '@/modules/index/src/common/tools';

export default {
  name: 'SalesPerson',
  components: {
    ImportExcel,
		Delete
  },
  // mixins: [emitter],
  props: {
  },
  data() {
    return {
			isShow: false,
      importExelDialogShow: false,
      dateRange: [],
      pageNo: 1,
      pageSize: 10,
      importRankDialog: false,
      total: 0,
      TbAgentInfoDTO: {
        id: '', // 查看详情的时候，传入id
        approvalId: '', // 流水号
        approvalStatus: '', // 审核状态  （审核的时候需要传的参数 0审核通过，1审核不通过 2 审核中【新增之后就是审核中】 ）
        auditReason: '', // 审核原因
        queryType: '', // 查询类型 0 增员 1人员维护 2 综合查询 3人员审核
        nameOrCode: '', // 如果业务员代码和姓名以在一个输入框里，就用这个字段
        agencyCode: '', // 机构代码
        tradeRegionCode: '', // 营业区编码
        tradeDeptCode: '', // 营业部编码
        personnelStatus: '', //  人员状态  【0待入职 1在职 2离职】 人员信息维护，人员状态必须要传1
        personnelRankCode: '', // 职级编码
        startTime: '', // 入司起始时间
        entTime: '', // 入司结束时间时间
        dimissionStartTime: '', // 离职开始时间
        dimissionEntTime: '', // 离职结束时间
        agentCode: '', //  业务员代码
        agentName: '' //    业务员名称
      },
      queryParam: {
        queryType: '0', // 查询类型 0 增员 1人员维护 2 综合查询 3人员审核
        certificationType: '0', // 证件类型
        certificateNum: '', // 证件号
        agencyCode: '', // 机构代码
        tradeRegionCode: '', // 营业区编码
        tradeDeptCode: '', // 营业部编码
        agentCode: '', //  业务员代码
        agentName: '', //    业务员名称
        approvalStatus: '', // 审核状态  （审核的时候需要传的参数 0审核通过，1审核不通过 2 审核中【新增之后就是审核中】 ）
        personnelStatus: '', //  人员状态  【0待入职 1在职 2离职】 人员信息维护，人员状态必须要传1
        personnelRankCode: '', // 职级编码
        startTime: '', // 入司起始时间
        entTime: '', // 入司结束时间时间
				crAgencyCode: getOper().c_login_dept_code, // 当前机构code
				crtCode: getOper().c_oper_code
      }, // 查询条件
      rows: [],
			currentRow: [],
      checkRow: null, // 单击选中的行
      selectIdxs: [],
      orgOption: [],
			rankOptions: [], // 职级
      regionOption: [],
      deptOption: [],
      approvalStatusOption: [], // 审核状态下拉
      personnelStatusOptions: [], // 人员状态
      documentTypeOptions: [], // 证件类型
    };
  },
  computed: {

  },
  created() {
    this.init();
  },
  mounted() {
  },
  methods: {
    init() {
      this.getOptions();
			this.query(); // 详情
    },
    getOptions() {
      Promise.all([
        getDictOptionsApi('approvalStatus'), // 审核状态
        getDictOptionsApi('personnelStatus'), // 人员状态
        getDictOptionsApi('documentType'), // 证件类型
        getDictOptionsApi('rank'), // 证件类型
				getOrgOptionAPi(),
				getRegionOptionAPi(),
				getDeptOptionAPi()
      ]).then((res) => {
        console.log('结果', res);
        this.approvalStatusOption = res[0].data; // 审核状态
        this.personnelStatusOptions = res[1].data; // 人员状态
        this.documentTypeOptions = res[2].data; // 证件类型
        this.rankOptions = res[3].data; // 人员职级
				this.orgOption = res[4].data; // 机构
				this.regionOption = res[5].data; // 区
				this.deptOption = res[6].data; // 部
      });
    },
    // 根据value 返回label
    optionShowLabel(option, value) {
      let label = '';
      if (option && option.length > 0) {
        option.forEach(i => {
          if (i.code === value) {
            label = i.name;
          }
        });
      }
      return label || value;
    },
    async getGetApprovalId() {
      const res = await getApprovalIdApi();
      console.log(res);
      // this.baseObj.approvalId = res.data.
    },
    handleSizeChange: function(val) {
      this.pageSize = val;
      this.query();
    },
    handleCurrentChange: function(val) { // 分页查询
      this.pageNo = val;
      this.query();
    },
    // 点击查询按钮方法
    searchQuery() {
      this.query();
    },
    // 重置方法
    reset() {
      this.checkRow = null;// 清空单击选中的行的数据
      this.$refs.queryParam.resetFields();
      this.$refs.table.setCurrentRow();// 取消高亮的行
			this.dateRange = [];
			this.queryParam.startTime = '';
			this.queryParam.endTime = '';
      this.query();
    },
    // 查询方法
    query() {
      this.checkRow = null;// 每次查询时清空单击选中的行的数据
      axios.post(PERFORM_URL + '/tbagentinfo/query_tbagentinfo_page',
        {
          pageNo: this.pageNo,
          pageSize: this.pageSize,
          ...this.queryParam
        }
      ).then((res) => {
        this.rows = res.data.records;
        this.total = res.data.total;
        // Message.success('查询成功');
      }).catch((res) => {
        Message.error({ message: res.message, duration: 2000 });
      });
    },

    // 新增行方法
    addRow() {
      // this.$router.push({ name: 'orgAgentManageAdd', params: { status: 'create' }});
      this.$router.push({ name: 'salesPersonAdd', params: { status: 'create' }});
    },
    // 编辑行
    editRow(row) {
      this.$router.push({ path: `/salesPersonSet/${row.approvalId}` });
      // this.$router.push({ name: 'salesPersonSet', params: { status: 'update', editInfo: row }});
    },
    // 删除
    async delRow(row) {
			this.currentRow = row;
			this.isShow = true;
      // const approvalId = row.approvalId;
      // console.log('删除', [approvalId]);
      // const res = await deletePersonAPi([approvalId]);
      // if (res) {
      //   this.query();
      // }
    },
    // 删除
    async deleteRow() {
      const approvalId = this.currentRow.approvalId;
      console.log('删除', [approvalId]);
      const res = await deletePersonAPi([approvalId]);
      if (res) {
        this.query();
      }
			this.isShow = false;
    },
    // 查看
    seeRow(row) {
			console.log('row', row);
			this.$router.push({ path: `/salesPersonInfo/${row.approvalId}` });
    },
    // 导出
    exportData() {
      const options = {
        url: AGENT_URL + '/org_agency/org_list_export',
        model: {
          ...this.queryParam
        },
        fileName: '机构管理',
        fileType: 'xlsx'
      };
      const url = options.url;
      const data = options.model;
      postFile(url, data, resp => {
        const blob = new Blob([resp], {
          type: 'application/vnd.ms-excel;charset=UTF-8'
        });
        const fileName = (options.fileName ? options.fileName : '下载文件') + '.' + options.fileType;
        if (window.navigator.msSaveBlob) {
          // 兼容IE浏览器
          window.navigator.msSaveBlob(blob, fileName);
        } else {
          const url = window.URL.createObjectURL(blob);
          const link = document.createElement('a');
          link.href = url;
          link.setAttribute('download', fileName);
          document.body.appendChild(link);
          link.click();
          document.body.removeChild(link); // 下载完成移除元素
          window.URL.revokeObjectURL(url); // 释放掉blob对象
        }
      }, err => {
        const message = err.message;
        err.message = message || '请求失败，请稍后重试!';
				Message.error({ message: err.message, duration: 2000 });
      });
    },
    // 导入
    importData() {
      this.importExelDialogShow = true;
    },
    // 下载模板
    importTemplate() {},
    // 单行数据被选中
    clickRow(row, column, event) {
      // console.log('单行数据被选中', row, column, event);
      this.checkRow = row;
    },
    selectRow(val) { // 行勾选事件
      if (val.length > 0) {
        this.selectIdxs = [];
        this.multipleSelection = [];
        for (var i in val) {
          this.selectIdxs.push(val[i].n_pk_id);
          this.multipleSelection.push(val[i].c_agency_agrmnt_no);
        }
      } else {
        this.selectIdxs = [];
        this.multipleSelection = [];
      }
    },
    // 下载模板
    downloadTemplate() {
      const options = {
        url: BASIC_SERVICE_URL + '/rank_conf/export_template',
        model: {},
        fileName: '职级导入模板',
        fileType: 'xlsx'
      };
      const url = options.url;
      const data = options.model;
      postFile(url, data, resp => {
        const blob = new Blob([resp], {
          type: 'application/vnd.ms-excel;charset=UTF-8'
        });
        const fileName = (options.fileName ? options.fileName : '下载文件') + '.' + options.fileType;
        if (window.navigator.msSaveBlob) {
          // 兼容IE浏览器
          window.navigator.msSaveBlob(blob, fileName);
        } else {
          const url = window.URL.createObjectURL(blob);
          const link = document.createElement('a');
          link.href = url;
          link.setAttribute('download', fileName);
          document.body.appendChild(link);
          link.click();
          document.body.removeChild(link); // 下载完成移除元素
          window.URL.revokeObjectURL(url); // 释放掉blob对象
        }
      }, err => {
        const message = err.message;
        err.message = message || '请求失败，请稍后重试!';
				Message.error({ message: err.message, duration: 2000 });
      });
    },
    // 查看行方法
    checkRowFn(row) {

      // this.$router.push({ name: 'black_info', params: { status: 'check', amlInfo: row }});
    },
    formatDate: function(row, column) {
      const v_data = row[column.property];
      if (v_data === null) {
        return null;
      }
      const date = new Date(v_data);
      var o = {
        'M+': date.getMonth() + 1, // 月份
        'd+': date.getDate(), // 日
        'h+': date.getHours(), // 小时
        'm+': date.getMinutes(), // 分
        's+': date.getSeconds(), // 秒
        'q+': Math.floor((date.getMonth() + 3) / 3), // 季度
        'S': date.getMilliseconds() // 毫秒
      };
      var fmt = 'yyyy-MM-dd';
      if (/(y+)/.test(fmt)) {
        fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length));
      }
      for (var k in o) {
        if (new RegExp('(' + k + ')').test(fmt)) {
          fmt = fmt.replace(RegExp.$1, (RegExp.$1.length === 1) ? (o[k]) : (('00' + o[k]).substr(('' + o[k]).length)));
        }
      }
      return fmt;
    },
    getTimeRange(value) {
			console.log('value', value);
      if (value && value.length > 0) {
        const arr = value.split(' - ');
        this.queryParam.startTime = arr[0];
        this.queryParam.entTime = arr[1];
      } else {
				this.queryParam.startTime = '';
        this.queryParam.entTime = '';
			}
    }
  }
};
</script>
<style lang="scss">
body .el-table__body-wrapper {
	overflow: auto !important;
}
.el-table th .cell, .el-table .el-table__header-wrapper {
	padding-bottom: 4px;
	overflow: hidden !important;
}

</style>
